/*
 * Author: Tom Ajayebi
 * Class: COIN 71
 * Filename: bike.js
 *
 * Date Created: 3/04/2009, updated 3/11/09 by Tyler
 * functionality: Admin page, pass in different queries to mysql to allow admin user
 * to input a new bike route. Or view a given set of rides.
 */

// The url of the php servlet that takes an SQL query for the world db and returns an
// XML document with the reply.

var URL = "mysqlQuery.php";
var myQUERY = null;
var xmlDoc  =  null;
var RESULTS = null;  
var SELECTED_DATE = null; // to hold a date object with currently selected query date

// Result of INSERT query, just give a message back to user if the insert succeed.
function insertQueryResult(){
    xmlDoc = this.req.responseText;

    //DEBUG: display returned xml for debug
    alert(xmlDoc);
    var resultNode = document.getElementById("AnswerResult");
    document.getElementById("AnswerResult").value = "";
    //displayText("AnswerResult","");
    //resultNode.firstChild.nodeValue += "Answer = " + xmlDoc ;
    //return false;
}

// Result of SELECT query, give the result back to the calling routine to do whatever they like.
// uses JSON formatted result.
function selectQueryResult(){

    jsonText = this.req.responseText;

	var ridesArray = eval( "(" + jsonText + ")");
	
	RESULTS = ridesArray.rides;
	
	updateRideListing();    // reads from RESULTS global var
	
    return false;
}


// construct a SQL query for retriving fields inside mysql.
function sendSelectQuery(date){
	var days = 14;
	var msPerDay = 1000 * 60 * 60 * 24;
	var fromMs = date.getTime() - (msPerDay * days);
	var toMs = date.getTime() + (msPerDay * days);
	// toConsole("date.getTime() = " + date.getTime() + ", msPerDay = " + msPerDay + ", days = " + days);
	// var fromDate = new Date(fromMs);
	var fromDate = date;
	var toDate = new Date(toMs);
	var select	= "q=SELECT id,title,city,start_point,date,time,leader,leader_phone,description,category,hilliness,mileage";
	var from		= " FROM mazaika1.rides";
	var fromStr	= " '" + formatDate(fromDate) + "'";
	var toStr		= " '" + formatDate(toDate) + "'";
	var where		= " WHERE date BETWEEN" + fromStr + " AND" + toStr;
	var order		= " ORDER BY date ASC, time ASC";
	var myQUERY = select + from + where + order;
	
 //call content loader with the query constructed.
 contentLoader = new net.ContentLoader(URL, selectQueryResult, errorFunction, "POST", myQUERY);
}

function leadingZeroes(value, width) {
	var s = "0000000000" + value;
	s = s.substr(s.length-width, s.length);
	return s;
}

function formatDate(date) {
	return date.getFullYear() + "-" + leadingZeroes(date.getMonth()+1, 2) + "-" + leadingZeroes(date.getDate(), 2);
}


// given time string in format: "08:30 pm", converts time to mysql 24-hour time format: HH:MM:SS
// Tyler, 3.16.09
function formatTime(timeString) {

	var formattedTime = null;	
	var times = timeString.split(":");				
	var hr = eval ( times[0] % 12 );				// hr gets string left of ":".
	var min = times[1].split(" ", 1)[0];			// min gets string left of " " from right side of timeString.split

	if ( timeString.search( /pm/i ) != -1 ) {		// if "pm" is in string, add 12 to value
		hr = ( hr + 12 );		
	}
	if ( hr < 10 ) { hr = "0"+hr ; } 				// prepend "0" to single-digit values;
	
	formattedTime = hr + ":" + min + ":00";

	return formattedTime;
}


//********************************************** WORK ON THIS *************************
//***************************************************************************************
// # = note left by tyler


// checks to see that a non-null value exists for all keys in array "values".  
// returns boolean.
// by Vern, modified by Tyler 3.16.09
function verifyAllFilled (values) {
	var result = true;
	for (var i = 0; result && i < values.length; i++) {
		if (!values[i]) result = false;					// changed from ("" = values[i])
	}
	return result;
}

// Grab user inputed data and INSERT it into mysql DB table
function sendInsertQuery(){
	var fields = ["title", "city", "start_point", "date", "time", "leader", "leader_phone", "description", "category", "hilliness", "mileage"]; // removed field photoURL
	var values = new Array();
	
	var title = document.getElementById("title").firstChild.nextSibling.value;
	var city = document.getElementById("city").firstChild.nextSibling.value;
	var start_point = document.getElementById("start_point").firstChild.nextSibling.value;
	var popupDatepicker = document.getElementById("popupDatepicker").value;
	var timepickr = document.getElementById("timepickr").value;
	var leader = document.getElementById("leader").firstChild.nextSibling.value;
	var phone_0 = document.getElementById("phone_0").value;
	var phone_1 = document.getElementById("phone_1").value;
	var phone_2 = document.getElementById("phone_2").value;
	var description = document.getElementById("description").firstChild.nextSibling.value;
	var category = document.getElementById("category").firstChild.nextSibling.value;
	var hilliness = document.getElementById("hilliness").firstChild.nextSibling.value;
	var mileage = document.getElementById("mileage").firstChild.nextSibling.value;	
	
	values.push(title);
	values.push(city);
	values.push(start_point);

	var date = new Date(popupDatepicker);
	date = formatDate(date);
	values.push(date);

	var time = formatTime(timepickr);				// new formatTime function by Tyler, 3.16.09
	values.push(time);
    
  	values.push(leader);
    	
	var phone = ""+phone_0+""+phone_1+""+phone_2;	// concatenate phone number parts to string.  tyler 3.16.09	
	values.push(phone);
	
	values.push( description);   
	
	values.push(category);
	values.push(hilliness);
	values.push(mileage);

	if (verifyAllFilled(values)) { 		// if passes primitive validation, insert into DB
    	var insert = "q=INSERT";

    	var into = " INTO mazaika1.rides (" + fields.toString() + ")";		// replaced commaSeparatedList function with toString().  tyler 3.16.09
    	var valuez = " VALUES (" + commaSeparatedList(values, "\"") + ")";
    	
    	var myQUERY = insert + into + valuez;

        contentLoader = new net.ContentLoader(URL, insertQueryResult, errorFunction, "POST", myQUERY);

        displayText("AnswerResult","Success: Record Inserted...");
        
        queryRides(SELECTED_DATE);
        
	} else {

	alert("Error: All Fields need to have a value..")
	}
    return false;
}


// converts an array of values into a string of comma-separated values in quotes
function commaSeparatedList(members, quoteMark) {
	var result = "";
	for (i = 0; i < members.length; i++) {
		if (quoteMark) result += quoteMark;
		result += members[i];
		if (quoteMark) result += quoteMark;
		result += ",";
	}
	result = result.slice(0, -1);

	return result;
}


// Clear user inputed data
//updated 3.16.09 by Tyler
function clearFields(){
    document.getElementById("title").firstChild.nextSibling.value="" ;
    document.getElementById("city").firstChild.nextSibling.value="" ;
    document.getElementById("start_point").firstChild.nextSibling.value="" ;
    document.getElementById("date").firstChild.nextSibling.value ="";
    document.getElementById("time").firstChild.nextSibling.value ="";
    document.getElementById("leader").firstChild.nextSibling.value ="";
    document.getElementById("leader_phone").firstChild.nextSibling.value ="";
    document.getElementById("phone_0").value ="";
    document.getElementById("phone_1").value ="";
    document.getElementById("phone_2").value =""
    document.getElementById("description").firstChild.nextSibling.value ="";
    document.getElementById("category").firstChild.nextSibling.selectedIndex =0;
    document.getElementById("hilliness").firstChild.nextSibling.selectedIndex =0;
    document.getElementById("mileage").firstChild.nextSibling.value ="";

    removeAllChildrens(document.getElementById("AnswerResult"));
}

// ****************************************************** END WORKING SECTION *****************
// *********************************************************************************************


// called by the ContentLoader when there is an error with the request
function errorFunction()
{	var answerNode = document.getElementById("Answer");
	answerNode.firstChild.nodeValue += "Error:  DB connection failed : " + this.req.responseText;
}

 /* Sets the name and id attributes of the new node to "nameId".
 * If "text" is present, this also creates a text node with "text" in it and appends it to the new node.
 * Returns the new node.
 * Adapted from page 8 of Crane and Pascarello
 */
function addNode(parent, element, nameId, text) {
  var newNode = document.createElement(element);
  parent.appendChild(newNode);
  newNode.setAttribute("id", nameId);
  newNode.setAttribute("name", nameId);
  if (text != "") {
    var textNode = document.createTextNode(text);
    newNode.appendChild(textNode);
  }
  return newNode;
}


 // this fucntion removes all of parent's children.
function removeAllChildrens(parent) {
  children = parent.childNodes;
  for (var i = children.length-1; i >=0; i--) {
    parent.removeChild(children[i]);
  }
}

 // Add a text to a document. Test a given divId and see if it has children,
 // if not create a Text Node,If it does, then change the text of the child
function displayText(DivId,text){
    var currentNode = document.getElementById(DivId);
    if (!currentNode.hasChildNodes()) {
        var prompt = document.createTextNode(text) ;
        currentNode.appendChild(prompt);
    }
    else {currentNode.firstChild.data  = text;}
}

// anything we add that later
function postAnnouncement()
{
	var XML_FILE = "announcements.xml";
	var titleValue = document.getElementById('title').value;
	var authorValue = document.getElementById('author').value;		
	var msgValue = document.getElementById('message').value;		
	var dateValue = document.getElementById('postdate').value;
	
	var xmlDoc=loadXMLDoc("announcements.xml");
		announcementsEl = xmlDoc.getElementsByTagName('announcements')[0];
		announceEl = xmlDoc.createElement('announcement');
		alert(announceEl);
		announcementsEl.appendChild(announceEl);
		
		//create title element
		addChildWText(xmlDoc,  announceEl, "title", titleValue);
		//create postedby element
		addChildWText(xmlDoc,  announceEl, "author", authorValue);
		//create message element
		addChildWText(xmlDoc,  announceEl, "message", msgValue);
		//create post_date element
		addChildWText(xmlDoc,  announceEl, "postdate", dateValue);
		
		xmlDoc.save("announcements.xml");

		queryRidesFromToday();
	//validate the form 
	/*var retVal = validateAnnouncement(titleValue, authorValue, msgValue);
	if (retVal.length != 0)
	{
		alert( retVal);
		return false;
	}
	else {
		
	
/*
			$XML_FILE = "announcements.xml";
	                $dom = new DOMDocument;
			$dom->formatOutput = true;
	                $dom->load($XML_FILE);
					

			//create announcement element
			$announceEl = $dom ->createElement('announcement');
			$announcementsEl -> appendChild($announceEl);
			//create title element
			addChildWText(xmlDoc,  $announceEl, "title", $_POST["title"]);
			//create postedby element
			addChildWText(xmlDoc,  $announceEl, "author", $_POST["author"]);
			//create message element
			addChildWText(xmlDoc,  $announceEl, "message", $_POST["message"]);
			//create post_date element
			addChildWText(xmlDoc,  $announceEl, "postdate", date('m/d/Y'));

			//save XML file with newly posted information.
			$test = $dom->save($XML_FILE);
			
	
	} */
}

function addChildWText (xmlDoc, parent, tagName, text ) {
    newTag = xmlDoc.createElement( tagName );
    newTag.appendChild( xmlDoc.createTextNode( text ));
    parent.appendChild( newTag );
}
